<?php
/**
 * Created by PhpStorm.
 * User: ZhuXueSong
 * Date: 2019-06-28
 * Time: 13:10
 */

namespace App\Services\Third;

use App\Http\Request;
use App\Models\RequestLog;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class Base
{
    protected $server_url  = null;
    protected $server_port = null;

    protected $client  = null;
    protected $headers = [];


    public function __construct($host, $port = 80)
    {
        $this->server_url  = $host;
        $this->server_port = $port;
        $this->client      = Request::client($host, $port);
    }

    /**
     * 修改请求域名
     * @param string $host
     * @param int $port
     * @return boolean
     */
    public function changeHost($host, $port = 80)
    {
        $this->client = Request::client($host, $port);
        return true;
    }

    /**
     * @param $uri
     * @param array $params
     * @param string $method
     * @param bool $isJson
     * @return array|mixed|string
     * @throws \Throwable
     */
    public function otherRequest($uri, $params = [], $method = Request::GET_METHOD, $isJson = !Request::IS_JSON)
    {
        return $this->request($uri, $params, $method, $isJson);
    }

    /**
     * @param string $uri
     * @param array $params
     * @param string $method
     * @param bool $isJson
     * @return array|mixed|string
     * @throws \Throwable
     */
    protected function request($uri, $params = [], $method = Request::GET_METHOD, $isJson = !Request::IS_JSON)
    {
        try {
            $requests = array_merge(Request::buildQuery($params, $method, $isJson), $this->headers ? ['headers' => $this->headers] : []);

            \Log::info("请求信息：" . json_encode($params, JSON_UNESCAPED_UNICODE));
            $response = $this->client->request($method, $uri, $requests);
            $result   = $response->getBody()->getContents();
            $result   = json_decode($result, true);
            \Log::info("响应信息：" . json_encode($result, JSON_UNESCAPED_UNICODE));
            return $result;
        } catch (RequestException $e) {
            if ($e->hasResponse()) {
                $result = $e->getResponse()->getBody()->getContents();
                $result = json_decode($result, true);
            } else {
                $result = ['code' => $e->getCode(), 'message' => $e->getMessage(), 'ext' => '请求失败'];
            }
            $result = $this->parseResult($result);
            RequestLog::log($this->server_url, $uri, $params, $result['code'], $result['message'], $result);
            throw $e;
        }
    }

    /**
     * @param $result
     * @return array
     */
    protected function parseResult($result)
    {
        return [
            'code'    => $result['code'] ?? 500,
            'message' => $result['message'] ?? '',
            'data'    => $result['data'] ?? ($result ?? []),
        ];
    }
}
